package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.Certificate;
import com.hnichr.ump.common.talent.library.service.CertificateService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class CertificateSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "certificateList";

    @Autowired
    private CertificateService certificateService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray certList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(certList)){
            return;
        }
        for(Object certObject:certList){
            if(certObject instanceof JSONObject){
                JSONObject cert = (JSONObject) certObject;
                Certificate certificate = new Certificate();
                certificate.setId(cert.getString("id"));
                certificate.setDelFlag(cert.getBoolean("delFlag"));
                certificate.setUserId(cert.getString("userId"));
                if(cert.containsKey("createTime")){
                    certificate.setOrginalCreateTime(new Date(cert.getLong("createTime")));
                }
                if(cert.containsKey("updateTime")){
                    certificate.setOrginalUpdateTime(new Date(cert.getLong("updateTime")));
                }

                certificate.setName(cert.getString("name"));
                certificate.setResumeId(cert.getString("resumeId"));
                if(cert.containsKey("time")){
                    certificate.setTime(new Date(cert.getLong("time")));
                }
                certificate.setLicenseIssuingUnit(cert.getString("licenseIssuingUnit"));
                certificate.setSyncDate(syncDate);
                certificateService.merge(certificate);
            }
        }
    }
}
